package com.community.service.impl;

import cn.hutool.crypto.digest.DigestAlgorithm;
import cn.hutool.crypto.digest.Digester;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.community.expection.CustomerException;
import com.community.mapper.AdminMapper;
import com.community.pojo.entity.Admin;
import com.community.service.AdminService;
import org.springframework.stereotype.Service;

import java.util.UUID;


@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements AdminService {

    @Override
    public void insertAdmin(Admin admin) {

        //1.查询用户名是否存在
        if(this.getOne(new QueryWrapper<Admin>().eq("username", admin.getUsername()))!=null){
            throw new CustomerException("用户名已经存在!");
        }

        //2.查询手机号码是否使用
        if (this.getOne(new QueryWrapper<Admin>().eq("phone", admin.getPhone()))!=null){
            throw new CustomerException("手机号码已经使用!");
        }

        //3.查询邮箱是否使用
        if (this.getOne(new QueryWrapper<Admin>().eq("email", admin.getEmail()))!=null){
            throw new CustomerException("邮箱已经使用!");
        }

        //4.生成盐
        String salt= UUID.randomUUID().toString();

        //5.密码加密
        Digester md5 = new Digester(DigestAlgorithm.MD5);

        String md5Password = md5.digestHex(admin.getPassword()+salt);


        //6.保存盐和加密后的密码
        admin.setSalt(salt);
        admin.setPassword(md5Password);

        //7.保存用户
        getBaseMapper().insert(admin);
    }


}